# -*- coding: utf-8 -*-
"""
Created on Mon Jul  8 09:57:20 2024
@author: xinyuan.wei
FIA Data Analysis
"""
import os
import pandas as pd
import matplotlib.pyplot as plt

# Get the current working directory
current_directory = os.getcwd()

# Get the parent directory
parent_directory = os.path.dirname(current_directory)
file_path = os.path.join(parent_directory, 'NE_Plot_Composition.csv')
data = pd.read_csv(file_path)

# Filter the data based on the given conditions
filtered_data = data[(data['CONDID'] == 1) & 
                     (data['CONDPROP_UNADJ'] >= 0.9) &
                     (data['eAG'] >= 1) &
                     (data['STDAGE'] <= 200)].copy()

# Group by 'STDAGE' and calculate mean and standard deviation 
grouped_stdage = filtered_data.groupby('STDAGE').agg({'eAG': ['mean', 'std']}).reset_index()
grouped_stdage.columns = ['STDAGE', 'eAG_mean', 'eAG_std']

save_file_path = os.path.join(parent_directory, 'Biomass_stand age.csv')
grouped_stdage.to_csv(save_file_path, index=False)

# Plot settings
plt.figure(figsize=(18, 12))

# Plot  Stand age (years)
plt.subplot(2, 1, 1)
mean_values = grouped_stdage['eAG_mean']
std_values = grouped_stdage['eAG_std']
ages = grouped_stdage['STDAGE']

plt.plot(ages, mean_values, 'k-', label='AGB (kg/m2)')
plt.fill_between(ages, mean_values - std_values, mean_values + std_values, 
                 color='blue', alpha=0.4)
plt.xlabel('Stand age (year)', fontsize=24)
plt.ylabel('AGB (kg/m2)', fontsize=24)
plt.grid(True)
plt.xlim(0, 130)  # Set x-axis range from 0 to 130
plt.xticks(range(0, 131, 10)) 
plt.tick_params(axis='both', which='major', labelsize=24)

plt.tight_layout()
plt.show()
